package com.tanchengjin.admin.aop.needPermission;

import com.tanchengjin.admin.aop.needRole.NeedRole;
import com.tanchengjin.admin.exception.ApplicationException;
import com.tanchengjin.admin.exception.NeedPermissionException;
import com.tanchengjin.admin.model.pojo.AdminPermission;
import com.tanchengjin.admin.service.AdministratorService;
import org.aspectj.lang.ProceedingJoinPoint;
import org.aspectj.lang.annotation.*;
import org.aspectj.lang.reflect.MethodSignature;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Component;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import java.lang.reflect.Method;
import java.util.List;

/**
 * @author TanChengjin
 * @version v1.0.0
 * @email 18865477815@163.com
 */
@Aspect
@Component
public class NeedPermissionAspect {
    private final static Logger logger = LoggerFactory.getLogger(NeedPermissionAspect.class);

    @Autowired
    private AdministratorService administratorService;

    @Pointcut(value = "@annotation(com.tanchengjin.admin.aop.needPermission.NeedPermission)")
    public void config() {

    }

    @Before("config()")
    public void before() {

    }

    @Around(value = "config()")
    public Object around(ProceedingJoinPoint point) throws Throwable {
        logger.info("around");
        //通过反射拿到注解
        Method m = ((MethodSignature) (point.getSignature())).getMethod();
        Method method = point.getTarget().getClass().getMethod(m.getName(), m.getParameterTypes());
        NeedPermission annotation = method.getAnnotation(NeedPermission.class);
        //获取注解中的权限
        String[] permission = annotation.value();
        String permissionStr = permission[0];
        List<AdminPermission> identifierPermission = administratorService.getIdentifierPermission();
        for (AdminPermission adminPermission : identifierPermission) {
            if (adminPermission.getIdentifier().equals(permissionStr)) {
                return point.proceed();
            }
        }

        NeedRole.ResponseType responseType = annotation.responseType();
        if (responseType == NeedRole.ResponseType.REST) {
            throw new NeedPermissionException("权限不足");
        } else if (responseType == NeedRole.ResponseType.HTML) {
            ServletRequestAttributes requestAttributes = (ServletRequestAttributes) (RequestContextHolder.getRequestAttributes());
            HttpServletRequest request = requestAttributes.getRequest();
            HttpServletResponse response = requestAttributes.getResponse();
            response.sendRedirect(request.getContextPath() + "/admin/auth/login");
        }

        return null;
    }

    @After("config()")
    public void after() {

    }
}
